package com.example.springcloud.order.config;

import io.seata.saga.engine.StateMachineEngine;
import io.seata.saga.engine.config.DbStateMachineConfig;
import io.seata.saga.engine.impl.ProcessCtrlStateMachineEngine;
import io.seata.saga.rm.StateMachineEngineHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * Saga 状态机配置
 */
@Slf4j
@Configuration
public class SagaConfiguration {

    @Bean
    public StateMachineEngine stateMachineEngine(DataSource dataSource) throws IOException {
        log.info("初始化 Saga 状态机引擎...");

        // 创建状态机配置
        DbStateMachineConfig stateMachineConfig = new DbStateMachineConfig();

        // 设置数据源
        stateMachineConfig.setDataSource(dataSource);

        // 设置应用 ID
        stateMachineConfig.setApplicationId("order-service");

        // 设置事务服务组
        stateMachineConfig.setTxServiceGroup("my_test_tx_group");

        // 设置状态机定义资源路径
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath*:saga/*.json");

        // 转换 Resource 数组为路径字符串数组
        String[] resourcePaths = new String[resources.length];
        for (int i = 0; i < resources.length; i++) {
            resourcePaths[i] = resources[i].getURL().toString();
        }
        stateMachineConfig.setResources(resourcePaths);

        // 是否开启异步提交
        stateMachineConfig.setEnableAsync(false);

        // 创建状态机引擎
        ProcessCtrlStateMachineEngine stateMachineEngine = new ProcessCtrlStateMachineEngine();
        stateMachineEngine.setStateMachineConfig(stateMachineConfig);

        log.info("Saga 状态机引擎初始化完成，加载了 {} 个状态机定义", resources.length);
        for (Resource resource : resources) {
            log.info("  - {}", resource.getFilename());
        }

        log.info("状态机引擎将在首次使用时自动加载定义并初始化");

        return stateMachineEngine;
    }
}

